const app = getApp()
import {
  showMsg
} from '../../../utils/config.js'
import {
  reqOrgList
} from '../../../request/api'
Page({
  data: {
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    dataList: [],
    page: 1,
    isNextPage: true,
    triggered: false, //是否下拉刷新列表

    orgItemInfo: {},

    unitLevelList: [],

    scrollToLastItem: "",
    selectId: "",
  },
  async onLoad(e) {
    this.setData({
      selectId: app.globalData.orgId
    })
    await this.getDataList()

    const orgId = app.globalData.orgId
    console.log('orgId', orgId);
    console.log('this.data.dataList', this.data.dataList);
    if (!orgId) return //没有orgId就是全部
    // console.log(this.findNodeById(this.data.dataList, orgId));
    // console.log('findPathById,', this.findPathById(this.data.dataList, orgId))

    let orgList = this.findPathById(this.data.dataList, orgId)
    let info = orgList[orgList.length - 1]
    // console.log('orgList', orgList);
    // console.log('info', info);

    let dataList = []
    let unitLevelList = []

    if (info.children && info.children.length) {
      unitLevelList = JSON.parse(JSON.stringify(orgList))
      dataList = info.children
    } else {
      unitLevelList = JSON.parse(JSON.stringify(orgList))
      unitLevelList.splice(unitLevelList.length - 1)
      if (unitLevelList && unitLevelList.length && unitLevelList[unitLevelList.length - 1].children) {
        dataList = unitLevelList[unitLevelList.length - 1].children
      } else {
        dataList = this.data.dataList
      }

    }


    this.setData({
      unitLevelList: unitLevelList,
      orgItemInfo: info,
      selectId: info.id,
      scrollToLastItem: `item${info.id || ""}`,
      page: 1,
      dataList
    })

  },
  onShow() {
    if (app.globalData.orgId) {
      this.getOrgInfo()
    }
  },
  getOrgInfo() {
    this.setData({
      'orgItemInfo.id': app.globalData.orgId,
      'orgItemInfo.orgName': app.globalData.orgName,
      'orgItemInfo.tenantId': app.globalData.orgId2,
    })
  },

  findNodeById(tree, targetId) {
    // 遍历树中的每个节点
    for (const node of tree) {
      // 如果当前节点的 id 匹配目标 id，则返回该节点
      if (node.id === targetId) {
        return node;
      }
      // 如果当前节点有子节点，递归查找子节点
      if (node.children && node.children.length > 0) {
        const result = this.findNodeById(node.children, targetId);
        if (result) {
          return result;
        }
      }
    }
    // 如果未找到匹配的节点，返回 null
    return null;
  },

  findPathById(tree, targetId) {
    // 递归查找函数
    function dfs(node, path) {
      // 将当前节点加入路径
      path.push(node);
      // 如果当前节点的 id 匹配目标 id，则返回路径
      if (node.id === targetId) {
        return path;
      }
      // 如果当前节点有子节点，递归查找子节点
      if (node.children && node.children.length > 0) {
        for (const child of node.children) {
          const result = dfs(child, [...path]); // 传递新的路径副本
          if (result) {
            return result;
          }
        }
      }
      // 如果未找到匹配的节点，返回 null
      return null;
    }

    // 遍历树中的每个节点
    for (const node of tree) {
      const result = dfs(node, []); // 从当前节点开始查找
      if (result) {
        return result;
      }
    }
    // 如果未找到匹配的节点，返回 null
    return null;
  },


  // 返回到全部单位
  onAllUnit() {
    this.setData({
      unitLevelList: [],
      orgItemInfo: {
        id: '',
        orgName: '全部'
      },
      selectId: "",
      page: 1
    })
    this.getDataList()
  },

  // 触发单个单位
  onPartUnit(e) {
    let info = e.currentTarget.dataset.item
    let index = this.data.unitLevelList.findIndex(item => item.id == info.id)
    this.data.unitLevelList.splice(index + 1)
    this.setData({
      unitLevelList: this.data.unitLevelList,
      orgItemInfo: info,
      selectId: info.id,
      scrollToLastItem: `item${info.id || ""}`,
      page: 1,
      dataList: info.children
    })

  },


  // 获取组织列表
  async getDataList() {
    let params = {
      tenantId: app.globalData.tenantId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      type: "1,2,3,4"
    }
    const res = await reqOrgList(params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    console.log('rows', rows);
    console.log('buildTree', this.buildTree(rows));
    this.setData({
      // totalData: [],
      dataList: this.buildTree(rows)
    })

  },
  buildTree(data) {
    const map = new Map();
    data.forEach((item) => {
      map.set(item.id, {
        ...item,
        children: []
      });
    });

    const tree = [];
    data.forEach((item) => {
      if (item.parentId === '0') {
        tree.push(map.get(item.id));
      } else {
        const parent = map.get(item.parentId);
        if (parent) {
          parent.children.push(map.get(item.id));
        } else {
          // 如果没有父节点，则作为根节点处理
          tree.push(map.get(item.id));
        }
      }
    });
    return tree;
  },

  itemClick(e) {
    let type = e.type
    let id = ''
    if (type == 'change') {
      id == e.detail
    } else {
      id = e.target.dataset.id
    }
    let {
      dataList
    } = this.data
    let orgItemInfo = {}
    dataList.forEach(item => {
      if (item.id === id) {
        orgItemInfo = item
      }
    })
    this.setData({
      orgItemInfo
    })
  },
  itemClick1(e) {
    let {
      item
    } = e.currentTarget.dataset
    this.setData({
      orgItemInfo: item,
      selectId: item.id,
    })
    // 有子级时才请求下一级
    if (item.children && item.children.length) {
      this.data.unitLevelList.push(item)
      this.setData({
        unitLevelList: this.data.unitLevelList,
        page: 1,
        scrollToLastItem: `item${item.id || ""}`,
      })
      // this.getDataList(item.id)
      this.setData({
        dataList: item.children
      })
    }
  },
  // 确认选择单位
  confirm() {
    let {
      id: orgId,
      orgName,
      type,
      role,
      flatType,
      tenantId
    } = this.data.orgItemInfo

    // if (!orgId) return showMsg("请选择一个组织机构登录")
    app.globalData.orgId = orgId
    wx.setStorageSync('orgId', orgId);
    app.globalData.orgName = orgName
    wx.setStorageSync('orgName', orgName);
    app.globalData.orgInfo = this.data.orgItemInfo
    wx.setStorageSync('orgInfo', this.data.orgItemInfo);
    app.globalData.orgId2 = tenantId
    wx.setStorageSync('orgId2', tenantId);
    app.globalData.flatType = flatType
    wx.setStorageSync('flatType', flatType);
    app.globalData.isTeamManager = role === 1 ? true : false //role为1：单位管理员 role为2：消防安全员
    wx.setStorageSync('isTeamManager', role === 1 ? true : false);

    // let unitLevelList = (this.data.unitLevelList && this.data.unitLevelList.length) ? JSON.stringify(this.data.unitLevelList) : null
    // app.globalData.unitLevelList = unitLevelList
    // wx.setStorageSync('unitLevelList', unitLevelList)

    // 传输数据到上个页面
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.emit('acceptData', {
      orgId,
      orgName,
      type
    });
    wx.navigateBack()
  },







  // 滚动到底部触发
  lower() {
    if (!this.data.isNextPage) return
    this.setData({
      page: this.data.page + 1,
    })
    this.getDataList()
  },
  // 下拉刷新
  async onRefresh() {
    this.setData({
      dataList: [],
      page: 1,
      isNextPage: true,
    })
    if (app.globalData.orgId) {
      this.getOrgInfo()
    }
    await this.getDataList()
    this.setData({
      triggered: false,
    })
  },
  // 点击复制编号
  clickCopy(e) {
    let {
      code
    } = e.currentTarget.dataset
    wx.setClipboardData({
      data: code,
      success(res) {
        wx.getClipboardData({
          success(res) {
            showMsg(`编号 ${code} 已复制`)
          }
        })
      }
    })
  },
})